package rabbitmq.rpc;

import com.rabbitmq.client.*;
import rabbitmq.constants.Constants;
import rabbitmq.utils.WorkUtils;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class Server {
    public static void main(String[] args) throws IOException, TimeoutException {
        ConnectionFactory factory = WorkUtils.createConnectionFactory();
        //建立连接
        Connection connection = factory.newConnection();
        //开启信道
        Channel channel = connection.createChannel();
        //声明队列
        channel.queueDeclare(Constants.RPC_QUEUE1,true,false,false,null);
        channel.queueDeclare(Constants.RPC_QUEUE2,true,false,false,null);
        //接收消息
        Consumer consumer = new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag,
                                       Envelope envelope,
                                       AMQP.BasicProperties properties,
                                       byte[] body) throws IOException {
                String s = new String(body);
                System.out.println("RPC [Server]接受消息成功：" + s);
                //发送消息
                AMQP.BasicProperties basicProperties = new AMQP.BasicProperties().builder()
                                .correlationId(properties.getCorrelationId())
                                .build();
                System.out.println(properties.getCorrelationId());
                channel.basicPublish("",Constants.RPC_QUEUE2,basicProperties,body);
                channel.basicAck(envelope.getDeliveryTag(),false);
            }
        };
        channel.basicConsume(Constants.RPC_QUEUE1,false,consumer);
    }
}
